#coding=utf-8
import requests,json
from flask import request
from api import test_report

	
	
'''获取项目名称'''
def get_subjectName(subject_id):
	if subject_id == 1:
		return 'ITS'
	
'''获取接口类型'''
def get_requestType(method):
	if method == 1:
		return 'Post'
	else:
		return 'Get'
	
	
	

class Request_Api():
	def __init__(self,host, url, method,parameter,expectation,depiction):
		
		self.host = host
		self.url=url
		# 接口类型
		self.method=method
		# 接口参数
		self.parameter = parameter
		# 用例期望
		self.expectation = expectation
		# 用例描述
		self.depiction = depiction
	
	
	def api(self):
		addres = self.host + self.url
		#expectation_dict=eval(self.expectation)
		'''method=1为Post请求,method=2为Get请求'''
		if self.method=='1':
			#如果有异常，本条用例标记'api_sta': 'error'，返回值为异常数据
			try:
				res=requests.request(method='POST', url=addres,data=json.dumps(self.parameter),verify=False)
				response_info = json.loads(str(res.text))
			except Exception as e:
				return {'api_sta': 'error', 'api_res': e}
			#判断请求状态码，非200返回'api_sta': 'error'
			if res.status_code==200:
				# self.expectation为空时，不进行断言。
				try:
					expectation_dict = eval(self.expectation)
				except Exception as e2:
					return {'api_sta': 'pass', 'api_res': response_info}
				# 断言遍历预期结果字典，如果失败返回'api_sta':'failed'，通过返回'api_sta': 'pass'
				for key in expectation_dict.keys():
					if expectation_dict[key]==response_info[key]:
						pass
					else:
						return {'api_sta':'failed','api_res':['断言失败,预期结果:'+str(key)+':'+str(expectation_dict[key]),
							'实际结果:'+str(key)+':'+str(response_info[key]),
							'返回数据:'+str(response_info)]}
				return {'api_sta': 'pass', 'api_res': response_info}
			else:
				return {'api_sta': 'error', 'api_res': response_info}
		elif self.method=='2':
			# 如果有异常，本条用例标记'api_sta': 'error'，返回值为异常数据
			try:
				res=requests.request(method='Get', url=addres, params=self.parameter)
				#response_info=json.loads(str(res.text))
				ss='{"code":0,"msg":"请求成功","userId":0,"token":null,"data":{"role":1,"videoPower":"1","snAuthPower":"1","userId":1,"token":"9f88cdad3c3b4e748e5367fb55cba90e"}}'
				response_info=json.loads(ss)
			except Exception as e:
				return {'api_sta': 'error', 'api_res': e}
			# 判断请求状态码，非200返回'api_sta': 'error'
			if res.status_code==200:
				# self.expectation为空时，不进行断言。
				try:
					expectation_dict = eval(self.expectation)
				except Exception as e2:
					return {'api_sta': 'pass', 'api_res': response_info}
				# 断言遍历预期结果字典，如果失败返回'api_sta':'failed'，通过返回'api_sta': 'pass'
				for key in expectation_dict.keys():
					if expectation_dict[key]==response_info[key]:
						pass
					else:
						return {'api_sta':'failed','api_res':['断言失败,预期结果:'+str(key)+':'+str(expectation_dict[key]),
							'实际结果:'+str(key)+':'+str(response_info[key]),
							'返回数据:'+ss]}
				return {'api_sta': 'pass', 'api_res': res.text}
			else:
				return {'api_sta': 'error', 'api_res': res.text}